"""
交易服务异常定义
================

定义交易服务中使用的各种业务异常类
提供统一的异常处理和错误信息管理
"""

# 确保项目根目录在Python路径中

# 统一路径管理
from backend.shared import PathManager
PathManager().setup_paths()
import sys
import os

from typing import Optional, Dict, Any

class TradingServiceError(Exception):
    """交易服务基础异常类"""
    
    def __init__(self, message: str, error_code: Optional[str] = None, details: Optional[Dict[str, Any]] = None):
        self.message = message
        self.error_code = error_code or "TRADING_ERROR"
        self.details = details or {}
        super().__init__(self.message)
    
    def to_dict(self) -> Dict[str, Any]:
        """转换为字典格式"""
        return {
            "error_code": self.error_code,
            "message": self.message,
            "details": self.details
        }

class OrderError(TradingServiceError):
    """订单相关异常基类"""
    pass

class OrderNotFoundError(OrderError):
    """订单不存在异常"""
    
    def __init__(self, order_id: str):
        super().__init__(
            message=f"订单不存在: {order_id}",
            error_code="ORDER_NOT_FOUND",
            details={"order_id": order_id}
        )

class OrderStatusError(OrderError):
    """订单状态错误异常"""
    
    def __init__(self, order_id: str, current_status: str, expected_status: str):
        super().__init__(
            message=f"订单状态错误，当前状态: {current_status}，期望状态: {expected_status}",
            error_code="ORDER_STATUS_ERROR",
            details={
                "order_id": order_id,
                "current_status": current_status,
                "expected_status": expected_status
            }
        )

class OrderValidationError(OrderError):
    """订单验证错误异常"""
    
    def __init__(self, message: str, field: Optional[str] = None, value: Optional[Any] = None):
        super().__init__(
            message=f"订单验证失败: {message}",
            error_code="ORDER_VALIDATION_ERROR",
            details={"field": field, "value": value}
        )

class InsufficientFundsError(TradingServiceError):
    """资金不足异常"""
    
    def __init__(self, required_amount: float, available_amount: float, currency: str = "CNY"):
        super().__init__(
            message=f"资金不足，需要: {required_amount} {currency}，可用: {available_amount} {currency}",
            error_code="INSUFFICIENT_FUNDS",
            details={
                "required_amount": required_amount,
                "available_amount": available_amount,
                "currency": currency
            }
        )

class PositionError(TradingServiceError):
    """持仓相关异常基类"""
    pass

class PositionNotFoundError(PositionError):
    """持仓不存在异常"""
    
    def __init__(self, symbol: str, user_id: str):
        super().__init__(
            message=f"持仓不存在: {symbol}",
            error_code="POSITION_NOT_FOUND",
            details={"symbol": symbol, "user_id": user_id}
        )

class InsufficientPositionError(PositionError):
    """持仓不足异常"""
    
    def __init__(self, symbol: str, required_volume: float, available_volume: float):
        super().__init__(
            message=f"持仓不足，需要: {required_volume}，可用: {available_volume}",
            error_code="INSUFFICIENT_POSITION",
            details={
                "symbol": symbol,
                "required_volume": required_volume,
                "available_volume": available_volume
            }
        )

class GatewayError(TradingServiceError):
    """网关相关异常基类"""
    pass

class GatewayNotFoundError(GatewayError):
    """网关不存在异常"""
    
    def __init__(self, gateway_name: str):
        super().__init__(
            message=f"网关不存在: {gateway_name}",
            error_code="GATEWAY_NOT_FOUND",
            details={"gateway_name": gateway_name}
        )

class GatewayNotConnectedError(GatewayError):
    """网关未连接异常"""
    
    def __init__(self, gateway_name: str):
        super().__init__(
            message=f"网关未连接: {gateway_name}",
            error_code="GATEWAY_NOT_CONNECTED",
            details={"gateway_name": gateway_name}
        )

class GatewayConnectionError(GatewayError):
    """网关连接异常"""
    
    def __init__(self, gateway_name: str, reason: str):
        super().__init__(
            message=f"网关连接失败: {gateway_name}，原因: {reason}",
            error_code="GATEWAY_CONNECTION_ERROR",
            details={"gateway_name": gateway_name, "reason": reason}
        )

class GatewayTimeoutError(GatewayError):
    """网关超时异常"""
    
    def __init__(self, gateway_name: str, timeout_seconds: int):
        super().__init__(
            message=f"网关超时: {gateway_name}，超时时间: {timeout_seconds}秒",
            error_code="GATEWAY_TIMEOUT",
            details={"gateway_name": gateway_name, "timeout_seconds": timeout_seconds}
        )

class StrategyError(TradingServiceError):
    """策略相关异常基类"""
    pass

class StrategyNotFoundError(StrategyError):
    """策略不存在异常"""
    
    def __init__(self, strategy_id: str):
        super().__init__(
            message=f"策略不存在: {strategy_id}",
            error_code="STRATEGY_NOT_FOUND",
            details={"strategy_id": strategy_id}
        )

class StrategyStateError(StrategyError):
    """策略状态错误异常"""
    
    def __init__(self, strategy_id: str, current_state: str, expected_state: str):
        super().__init__(
            message=f"策略状态错误，当前状态: {current_state}，期望状态: {expected_state}",
            error_code="STRATEGY_STATE_ERROR",
            details={
                "strategy_id": strategy_id,
                "current_state": current_state,
                "expected_state": expected_state
            }
        )

class StrategyExecutionError(StrategyError):
    """策略执行异常"""
    
    def __init__(self, strategy_id: str, reason: str):
        super().__init__(
            message=f"策略执行失败: {strategy_id}，原因: {reason}",
            error_code="STRATEGY_EXECUTION_ERROR",
            details={"strategy_id": strategy_id, "reason": reason}
        )

class RiskError(TradingServiceError):
    """风控相关异常基类"""
    pass

class RiskCheckFailedError(RiskError):
    """风控检查失败异常"""
    
    def __init__(self, risk_type: str, message: str, risk_level: str = "HIGH"):
        super().__init__(
            message=f"风控检查失败: {message}",
            error_code="RISK_CHECK_FAILED",
            details={
                "risk_type": risk_type,
                "risk_level": risk_level,
                "risk_message": message
            }
        )

class RiskLimitExceededError(RiskError):
    """风险限额超限异常"""
    
    def __init__(self, limit_type: str, current_value: float, limit_value: float):
        super().__init__(
            message=f"风险限额超限: {limit_type}，当前值: {current_value}，限额: {limit_value}",
            error_code="RISK_LIMIT_EXCEEDED",
            details={
                "limit_type": limit_type,
                "current_value": current_value,
                "limit_value": limit_value
            }
        )

class MarketDataError(TradingServiceError):
    """行情数据相关异常基类"""
    pass

class MarketDataNotFoundError(MarketDataError):
    """行情数据不存在异常"""
    
    def __init__(self, symbol: str, exchange: str):
        super().__init__(
            message=f"行情数据不存在: {symbol}.{exchange}",
            error_code="MARKET_DATA_NOT_FOUND",
            details={"symbol": symbol, "exchange": exchange}
        )

class MarketDataStaleError(MarketDataError):
    """行情数据过期异常"""
    
    def __init__(self, symbol: str, last_update_time: str, max_age_seconds: int):
        super().__init__(
            message=f"行情数据过期: {symbol}，最后更新时间: {last_update_time}",
            error_code="MARKET_DATA_STALE",
            details={
                "symbol": symbol,
                "last_update_time": last_update_time,
                "max_age_seconds": max_age_seconds
            }
        )

class ContractError(TradingServiceError):
    """合约相关异常基类"""
    pass

class ContractNotFoundError(ContractError):
    """合约不存在异常"""
    
    def __init__(self, symbol: str, exchange: str):
        super().__init__(
            message=f"合约不存在: {symbol}.{exchange}",
            error_code="CONTRACT_NOT_FOUND",
            details={"symbol": symbol, "exchange": exchange}
        )

class ContractNotTradableError(ContractError):
    """合约不可交易异常"""
    
    def __init__(self, symbol: str, exchange: str, reason: str):
        super().__init__(
            message=f"合约不可交易: {symbol}.{exchange}，原因: {reason}",
            error_code="CONTRACT_NOT_TRADABLE",
            details={"symbol": symbol, "exchange": exchange, "reason": reason}
        )

class DatabaseError(TradingServiceError):
    """数据库相关异常基类"""
    pass

class DatabaseConnectionError(DatabaseError):
    """数据库连接异常"""
    
    def __init__(self, reason: str):
        super().__init__(
            message=f"数据库连接失败: {reason}",
            error_code="DATABASE_CONNECTION_ERROR",
            details={"reason": reason}
        )

class DatabaseTransactionError(DatabaseError):
    """数据库事务异常"""
    
    def __init__(self, operation: str, reason: str):
        super().__init__(
            message=f"数据库事务失败: {operation}，原因: {reason}",
            error_code="DATABASE_TRANSACTION_ERROR",
            details={"operation": operation, "reason": reason}
        )

class CacheError(TradingServiceError):
    """缓存相关异常基类"""
    pass

class CacheConnectionError(CacheError):
    """缓存连接异常"""
    
    def __init__(self, reason: str):
        super().__init__(
            message=f"缓存连接失败: {reason}",
            error_code="CACHE_CONNECTION_ERROR",
            details={"reason": reason}
        )

class ConfigurationError(TradingServiceError):
    """配置相关异常基类"""
    pass

class InvalidConfigurationError(ConfigurationError):
    """无效配置异常"""
    
    def __init__(self, config_key: str, config_value: Any, reason: str):
        super().__init__(
            message=f"无效配置: {config_key}={config_value}，原因: {reason}",
            error_code="INVALID_CONFIGURATION",
            details={"config_key": config_key, "config_value": config_value, "reason": reason}
        )

class AuthenticationError(TradingServiceError):
    """认证相关异常基类"""
    pass

class AuthorizationError(TradingServiceError):
    """授权相关异常基类"""
    pass

class PermissionDeniedError(AuthorizationError):
    """权限不足异常"""
    
    def __init__(self, required_permission: str, user_id: str):
        super().__init__(
            message=f"权限不足，需要权限: {required_permission}",
            error_code="PERMISSION_DENIED",
            details={"required_permission": required_permission, "user_id": user_id}
        )

class RateLimitExceededError(TradingServiceError):
    """限流异常"""
    
    def __init__(self, limit_type: str, current_rate: int, max_rate: int):
        super().__init__(
            message=f"请求频率超限: {limit_type}，当前频率: {current_rate}，最大频率: {max_rate}",
            error_code="RATE_LIMIT_EXCEEDED",
            details={"limit_type": limit_type, "current_rate": current_rate, "max_rate": max_rate}
        )

class ServiceUnavailableError(TradingServiceError):
    """服务不可用异常"""
    
    def __init__(self, service_name: str, reason: str):
        super().__init__(
            message=f"服务不可用: {service_name}，原因: {reason}",
            error_code="SERVICE_UNAVAILABLE",
            details={"service_name": service_name, "reason": reason}
        )

class ExternalServiceError(TradingServiceError):
    """外部服务异常基类"""
    pass

class ExternalServiceTimeoutError(ExternalServiceError):
    """外部服务超时异常"""
    
    def __init__(self, service_name: str, timeout_seconds: int):
        super().__init__(
            message=f"外部服务超时: {service_name}，超时时间: {timeout_seconds}秒",
            error_code="EXTERNAL_SERVICE_TIMEOUT",
            details={"service_name": service_name, "timeout_seconds": timeout_seconds}
        )

class ExternalServiceUnavailableError(ExternalServiceError):
    """外部服务不可用异常"""
    
    def __init__(self, service_name: str, status_code: Optional[int] = None):
        super().__init__(
            message=f"外部服务不可用: {service_name}",
            error_code="EXTERNAL_SERVICE_UNAVAILABLE",
            details={"service_name": service_name, "status_code": status_code}
        )

# 异常映射字典，用于统一异常处理
EXCEPTION_MAPPING = {
    # 订单异常
    "ORDER_NOT_FOUND": OrderNotFoundError,
    "ORDER_STATUS_ERROR": OrderStatusError,
    "ORDER_VALIDATION_ERROR": OrderValidationError,
    
    # 资金异常
    "INSUFFICIENT_FUNDS": InsufficientFundsError,
    
    # 持仓异常
    "POSITION_NOT_FOUND": PositionNotFoundError,
    "INSUFFICIENT_POSITION": InsufficientPositionError,
    
    # 网关异常
    "GATEWAY_NOT_FOUND": GatewayNotFoundError,
    "GATEWAY_NOT_CONNECTED": GatewayNotConnectedError,
    "GATEWAY_CONNECTION_ERROR": GatewayConnectionError,
    "GATEWAY_TIMEOUT": GatewayTimeoutError,
    
    # 策略异常
    "STRATEGY_NOT_FOUND": StrategyNotFoundError,
    "STRATEGY_STATE_ERROR": StrategyStateError,
    "STRATEGY_EXECUTION_ERROR": StrategyExecutionError,
    
    # 风控异常
    "RISK_CHECK_FAILED": RiskCheckFailedError,
    "RISK_LIMIT_EXCEEDED": RiskLimitExceededError,
    
    # 行情异常
    "MARKET_DATA_NOT_FOUND": MarketDataNotFoundError,
    "MARKET_DATA_STALE": MarketDataStaleError,
    
    # 合约异常
    "CONTRACT_NOT_FOUND": ContractNotFoundError,
    "CONTRACT_NOT_TRADABLE": ContractNotTradableError,
    
    # 系统异常
    "DATABASE_CONNECTION_ERROR": DatabaseConnectionError,
    "DATABASE_TRANSACTION_ERROR": DatabaseTransactionError,
    "CACHE_CONNECTION_ERROR": CacheConnectionError,
    "INVALID_CONFIGURATION": InvalidConfigurationError,
    "PERMISSION_DENIED": PermissionDeniedError,
    "RATE_LIMIT_EXCEEDED": RateLimitExceededError,
    "SERVICE_UNAVAILABLE": ServiceUnavailableError,
    "EXTERNAL_SERVICE_TIMEOUT": ExternalServiceTimeoutError,
    "EXTERNAL_SERVICE_UNAVAILABLE": ExternalServiceUnavailableError
}

def create_exception(error_code: str, message: str, details: Optional[Dict[str, Any]] = None) -> TradingServiceError:
    """根据错误码创建对应的异常实例"""
    exception_class = EXCEPTION_MAPPING.get(error_code, TradingServiceError)
    
    if exception_class == TradingServiceError:
        return TradingServiceError(message, error_code, details)
    
    # 对于特定异常类，尝试使用详情中的参数创建实例
    if details:
        try:
            return exception_class(**details)
        except TypeError:
            # 如果参数不匹配，回退到基础异常
            return TradingServiceError(message, error_code, details)
    
    return TradingServiceError(message, error_code, details)

# 导出所有异常类
__all__ = [
    # 基础异常
    "TradingServiceError",
    
    # 订单异常
    "OrderError", "OrderNotFoundError", "OrderStatusError", "OrderValidationError",
    
    # 资金异常
    "InsufficientFundsError",
    
    # 持仓异常
    "PositionError", "PositionNotFoundError", "InsufficientPositionError",
    
    # 网关异常
    "GatewayError", "GatewayNotFoundError", "GatewayNotConnectedError", 
    "GatewayConnectionError", "GatewayTimeoutError",
    
    # 策略异常
    "StrategyError", "StrategyNotFoundError", "StrategyStateError", "StrategyExecutionError",
    
    # 风控异常
    "RiskError", "RiskCheckFailedError", "RiskLimitExceededError",
    
    # 行情异常
    "MarketDataError", "MarketDataNotFoundError", "MarketDataStaleError",
    
    # 合约异常
    "ContractError", "ContractNotFoundError", "ContractNotTradableError",
    
    # 系统异常
    "DatabaseError", "DatabaseConnectionError", "DatabaseTransactionError",
    "CacheError", "CacheConnectionError",
    "ConfigurationError", "InvalidConfigurationError",
    "AuthenticationError", "AuthorizationError", "PermissionDeniedError",
    "RateLimitExceededError", "ServiceUnavailableError",
    
    # 外部服务异常
    "ExternalServiceError", "ExternalServiceTimeoutError", "ExternalServiceUnavailableError",
    
    # 工具函数
    "create_exception", "EXCEPTION_MAPPING"
]